$(function () {
    //商品数据
    var shopMap = {};
    //选中的优惠和活动
    var salesMap = {
        'couponCode':"",
        "activityId":0
    };

    //获取商品列表
    getPayOrderShopList();

    var payStatus = true;
    $("body").on("click","#pay-list-box>li",function () {//选择支付类型
        var status = $(this).data('status');
        if(status!=1){
            return;
        }
        $("#pay-list-box>li").removeClass('dc-active');
        $(this).addClass("dc-active");
        var payType = $(this).data('type');
        $("#payType").val(payType);
    }).on('click',"#go-to-pay",function () {//去支付
        if(payStatus==false){
            return;
        }
        var params = {
            'payType':$("#payType").val(),
            'orderType': $("#orderType").val(),
            'shopData': $("#shopData").val(),
            'activityId':salesMap.activityId,
            'code':salesMap.couponCode
        };
        $.ajax({
            url: baseloaction +'/mobile/uc/order/createPayOrder',
            type:'post',
            dataType:'json',
            data:JSON.stringify(params),
            contentType:'application/json;charset=utf-8',
            beforeSend:function () {
                payStatus = false;
                return true;
            },
            success:function (result) {
                payStatus = true;
                if(result.success==true){
                    var order = result.entity;
                    if (order.orderStatus == 'SUCCESS') {//已支付成功
                        window.location.href = baseloaction +'/mobile/pay/payMessage?orderNo='+order.orderNo+"&type=2";
                    }else if (order.orderStatus == 'INIT') {//未支付成功
                        window.location.href = baseloaction + result.url;
                    }
                }else{
                    $.toast(result.message);
                }
            },
            error:function (error) {
                $.toast('系统错误，订单创建失败');
            }
        });
    });

    /**
     * 获取商品数据列表
     */
    function getPayOrderShopList() {
        $.ajax({
            url:baseloaction +'/mobile/uc/order/getPayOrderShopList',
            type:'post',
            dataType:'json',
            data:{
                'orderType':orderType,
                'shopData':shopData,
                'activityId':salesMap.activityId,
                'couponCode':salesMap.couponCode
            },
            success:function (result) {
                if(result.success==true){
                    showShopHtml(result.entity);
                    var orderPrice = result.entity.orderPrice;
                    showShopPrice(orderPrice);

                    //初始化充值价格
                    if(orderType=='ACCOUNT'){
                        initAccountPrice();
                    }
                    var filterActivity = false,filterCode =false;
                    if(salesMap.activityId > 0){
                        filterActivity = true;
                    }
                    if(salesMap.couponCode !=''){
                        filterCode = true;
                    }
                    if(filterCode== false || filterActivity==false){
                        //加载可使用的优惠券和活动
                        findOrderAvailableActivityAndCode(filterActivity,filterCode);
                    }
                }else{
                    $.toast(result.message);
                }
            },
            error:function (error) {
                $.toast('系统错误，商品数据获取失败');
            }
        });
    }

    /**
     * 显示商品数据
     * @param data
     */
    function showShopHtml(data) {
        //商品数量
        var shopNum = data.shopNum;
        $("#shop-num-box").text(shopNum);
        //商品列表
        var shopList = data.shopList;
        var context = '';
        $.each(shopList,function (index,shop) {
            shopMap[shop.shopId] = {
                shopId: shop.shopId,
                shopType: shop.shopType,
                name: shop.shopName,
                price:shop.realPrice,
                buyNum: shop.buyNum
            };
            context += '<li class="item-content '+(shop.shopType=='ACCOUNT'?'item-link':'')+'">';
            if(shop.shopType=='COURSE'){
                context += '<div class="item-media">';
                context += '<div class="wm-item-picture__wrap pr">';
                context+='<img class="wm-img" src="'+shop.course.imageMap.mobileUrlMap.small+'" alt="'+shop.shopName+'"/>';
                context += ' </div></div>';
            }
            context += '<div class="item-inner">';
            context += '<div class="item-title">';

            if(shop.shopType=='COURSE'){
                context += '<span class="fs7 c-666">[课程]'+shop.shopName+'</span>';
            }
            if(shop.shopType=='MEMBER'){
                context += '<span class="c-orange mr5 vam"><em style="font-size: .9rem;" class="iconfont icon-huiyuan"></em></span><samp>'+shop.shopName+'</samp>';
            }
            if(shop.shopType=='EXAM'){
                context += '<span class="fs7 c-666">[考试]'+shop.shopName+'</span>';
            }
            if(shop.shopType=='QA'){
                context += '<span class="fs7 c-666">[问答]'+shop.shopName+'</span>';
            }
            if(shop.shopType=='ATTEND'){
                context += '<span class="fs7 c-666">[旁听]'+shop.shopName+'</span>';
            }
            if(shop.shopType=='ACCOUNT'){
                context += '[充值]充值金额';
            }
            context += '</div>';
            if(shop.shopType !='ACCOUNT'){
                context +='<div class="item-after">';
                context +='<strong class="c-red fs7">';
                context +='<small class="fs4">￥</small>';
                context +='<samp></samp>';
                context +='<samp>'+parseFloat(shop.realPrice).toFixed(2)+'</samp>';
                context +='</strong>';
                context +='</div>';
            }
            if(shop.shopType=='ACCOUNT'){
                context += '<div class="item-input text-right">';
                if(shop.realPrice ==1){
                    context += '<input placeholder="1元尝鲜" id="amountCharge" readonly="readonly" type="text"/>';
                }
                if(shop.realPrice !=1){
                    context += '<input placeholder="'+shop.realPrice+'元" id="amountCharge" readonly="readonly" type="text"/>';
                }
                context += '</div>';
            }
            context += '</div></li>';
        });
        $("#mobile-shop-list-bx").html(context);
    }

    /**
     * 显示商品价格
     * @param orderPrice 价格对象
     */
    function showShopPrice(orderPrice) {
        $("#memberSubPrice").text(parseFloat(orderPrice.memberSubPrice).toFixed(2));
        if(orderPrice.memberSubPrice > 0){
            $("#memberSubPrice").parent().removeClass('hide');
        }else{
            $("#memberSubPrice").parent().addClass('hide');
        }
        $("#shop-price-box").text(parseFloat(orderPrice.realPrice).toFixed(2));
        $("#real-price").text(parseFloat(orderPrice.realPrice).toFixed(2));

        var balance = $("#balance").val();
        if(balance >= orderPrice.realPrice){
            $("#account-balance-box").removeClass('c-bbb');
            $("#account-balance-box").parents('li').addClass('dc-active');
            $("#payType").val("ACCOUNT");
            $("#account-balance-box").parents('li').data('status',1);
            $("#account-balance-box").parents('li').attr('data-status',1);
        }else{
            $("#account-balance-box").addClass('c-bbb');
            $("#account-balance-box").parents('li').removeClass('dc-active');

            var payTypeEm;
            if(orderType=='COMMON'){
                $($("#pay-list-box").find('li')[0]).data('status',0);
                $($("#pay-list-box").find('li')[0]).attr('data-status',0);
                payTypeEm = $($("#pay-list-box").find('li')[1]);
            }else{
                payTypeEm = $($("#pay-list-box").find('li')[0]);
            }
            payTypeEm.addClass('dc-active');
            $("#payType").val(payTypeEm.data('type'));
        }
    }

    /**
     * 加载优惠和活动
     */
    function findOrderAvailableActivityAndCode(filterActivity,filterCode) {
        if(orderType=='COMMON'){
            setTimeout(function () {
                var paramsList = new Array();
                $.each(shopMap,function (index,shop) {
                    if(index !=0){
                        paramsList.push({
                            'shopType':shop.shopType,
                            'price':shop.price+'',
                            'shopId':shop.shopId+''
                        });
                    }
                });
                $.ajax({
                    url:baseloaction +'/mobile/uc/order/findOrderAvailableActivityAndCode?filterActivity='+filterActivity+'&filterCode='+filterCode,
                    type:"post",
                    dataType:'json',
                    data:JSON.stringify(paramsList),
                    contentType:'application/json;charset=utf-8',
                    success:function (result) {
                        var activityList = result.activityList;
                        var couponCodeList = result.couponCodeList;

                        if(filterActivity ==false) {
                            if (activityList != null && activityList.length > 0) {
                                showActivityHtml(activityList);
                            }
                        }
                        if(filterCode==false) {
                            if (couponCodeList != null && couponCodeList.length > 0) {
                                showCouponCodeHtml(couponCodeList);
                            }
                        }
                    },
                    error:function (error) {
                        Zepto.toast(0,'','系统错误，活动和优惠加载失败');
                    }
                });
            });
        }
    }

    //初始化充值价格
    function initAccountPrice() {
        //选择充值金额
        $("#amountCharge").picker({
            toolbarTemplate: '<header class="bar bar-nav">\
                                      <button class="button button-link pull-right close-picker">确定</button>\
                                      <h1 class="title">账户充值</h1>\
                                      </header>',
            cols: [
                {
                    textAlign: 'left',
                    values: [
                        '1元尝鲜<p style=\'display: none;\'>@1</p>',
                        '19元<p style=\'display: none;\'>@19</p>',
                        '99元<p style=\'display: none;\'>@99</p>',
                        '199元<p style=\'display: none;\'>@199</p>',
                        '399元<p style=\'display: none;\'>@399</p>'
                    ]
                }
            ],
            onClose:function (p) {
                var value = p.value[0];
                value = value.replace(/<[^>]+>/g,'');
                var _arr = value.split("@");
                window.location.href = baseloaction + '/mobile/uc/order/initPayOrder?orderType=ACCOUNT&shopData=0-ACCOUNT-'+_arr[1];
            },
            formatValue:function (p,values,displayValues) {
                var val = values[0];
                val = val.replace(/<[^>]+>/g,'');
                var _arr = val.split("@");
                val = _arr[0];
                return val;
            }
        });
    }

    /**
     * 显示活动内容
     * @param activityList 活动列表
     */
    function showActivityHtml(activityList) {
        $(".yh-div-box").removeClass("hide");
        $("#hou-dong-bx").show();
        if(activityList!=null && activityList.length>0){
            var arr = new Array();
            arr.push("请选择限时活动...<p style=\'display: none;\'>@0</p>");
            $.each(activityList,function (index,e) {
                arr.push(e.activityName+'<p style=\'display: none;\'>@'+e.id+'</p>');
            });
            //选择活动
            $("#huoDong").picker({
                toolbarTemplate: '<header class="bar bar-nav">\
                                      <button class="button button-link pull-right close-picker">确定</button>\
                                      <h1 class="title">限时活动</h1>\
                                      </header>',
                cols: [
                    {
                        textAlign: 'left',
                        values: arr
                    }
                ],
                onClose:function (p) {
                    getPayOrderShopList();
                },
                formatValue:function (p,values,displayValues) {
                    var val = values[0];
                    val = val.replace(/<[^>]+>/g,'');
                    var _arr = val.split("@");
                    val = _arr[0];
                    salesMap.activityId = _arr[1];
                    return val;
                }
            });
        }else{
            $("#hou-dong-bx").remove();
        }
    }

    /**
     * 显示优惠券内容
     * @param couponCodeList 优惠券列表
     */
    function showCouponCodeHtml(couponCodeList){
        $(".yh-div-box").removeClass("hide");
        $("#you-hui-quan-bx").show();
        if(couponCodeList != null && couponCodeList.length > 0){
            var arr = new Array();
            arr.push("请选择优惠券...<p style='display: none;'>@</p>");
            $.each(couponCodeList,function (index,e) {
                var s = '';
                if(e.type==1){
                    s="满"+e.coupon.minAmount+'打'+e.coupon.limitAtion+'折<p style=\'display: none;\'>@'+e.code+'</p>';
                }else if(e.type==2){
                    s="满"+e.coupon.minAmount+'立减'+e.coupon.limitAtion+'<p style=\'display: none;\'>@'+e.code+'</p>';
                }
                arr.push(e.coupon.title+"-"+s);
            });
            //选择优惠券
            $("#youhuiQuan").picker({
                toolbarTemplate: '<header class="bar bar-nav">\
                                      <button class="button button-link pull-right close-picker">确定</button>\
                                      <h1 class="title">优惠券</h1>\
                                      </header>',
                cols: [
                    {
                        textAlign: 'left',
                        values:arr
                    }
                ],
                onClose:function (p) {
                    getPayOrderShopList();
                },
                formatValue:function (p,values,displayValues) {
                    var val = values[0];
                    val = val.replace(/<[^>]+>/g,'');
                    var _arr = val.split("@");
                    val = _arr[0];
                    salesMap.couponCode = _arr[1];
                    return val;
                }
            });
        }else{
            $("#you-hui-quan-bx").remove();
        }
    }
});